<script setup>
import { ref, reactive, nextTick, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { usetikuUserStore } from '@/stores/sj-user'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = usetikuUserStore()

const loginForm = reactive({
  username: '',
  password: ''
})

const loading = ref(false)
const rules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
}

const formRef = ref(null)
const route = useRoute() // 获取当前路由信息

const handleLogin = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        await userStore.login(
          loginForm.username, 
          loginForm.password
        )
        
        // 检查用户角色是否允许登录系统
        const allowedRoles = ['管理员', '学科组长', '教师']
        if (!allowedRoles.includes(userStore.userInfo.roleName)) {
          // 如果角色不允许登录，则清除登录信息并显示错误提示
          localStorage.removeItem('token')
          localStorage.removeItem('userInfo')
          userStore.logout()
          ElMessage.error('您的角色无权登录该系统')
          return
        }
        
        ElMessage.success('登录成功')
        await nextTick()
        // 强制刷新用户信息后再跳转
        await router.push('/home/dashboard')
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.response?.data?.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}

const goToForgetPassword = () => {
  router.push('/forget-password')
}

// 组件挂载后检查路由参数
onMounted(() => {
  if (route.query.error === 'role_not_allowed') {
    ElMessage.error('您的角色无权登录该系统')
    // 可选：清除可能残留的无效 token 和 userInfo
    localStorage.removeItem('token')
    localStorage.removeItem('userInfo')
    // 清除 URL 中的 error 参数，避免刷新页面时重复提示
    router.replace({ query: {} })
  }
})
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>题库管理系统</h2>
        <p>欢迎登录</p>
      </div>
      
      <el-form
        ref="formRef"
        :model="loginForm"
        :rules="rules"
        label-position="top"
        class="login-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input 
            v-model="loginForm.username" 
            placeholder="请输入用户名"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password">
          <el-input 
            v-model="loginForm.password" 
            type="password" 
            placeholder="请输入密码"
            prefix-icon="Lock"
            @keyup.enter="handleLogin"
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-button 
            type="primary" 
            :loading="loading" 
            @click.prevent="handleLogin"
            class="login-button"
          >
            登录
          </el-button>
          
          <div class="forget-password">
            <a @click="goToForgetPassword">忘记密码?</a>
          </div>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  font-size: 24px;
  color: #303133;
  margin-bottom: 10px;
}

.login-header p {
  font-size: 14px;
  color: #909399;
}

.login-form {
  margin-top: 20px;
}

.form-actions {
  margin-top: 30px;
}

.login-button {
  width: 100%;
  padding: 12px 0;
}

.forget-password {
  text-align: right;
  margin-top: 15px;
  font-size: 14px;
}

.forget-password a {
  color: #409eff;
  cursor: pointer;
}
</style>